package ymbky.firstcodesunnyweather.planbook

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import java.util.ArrayList
//创建数据库帮助类
class RecordDbOpenHelper(context: Context?):SQLiteOpenHelper(context, DB_NAME, null, 1) {
    companion object {
        private const val DB_NAME = "recordQLite.db"
        private const val TABLE_NAME_NOTE = "record"
        private const val CREATE_TABLE_SQL ="create table " + TABLE_NAME_NOTE +
                " (id integer primary key autoincrement, title text, affair text, create_time text)"
    }

    override fun onCreate(db: SQLiteDatabase) {
        db.execSQL(CREATE_TABLE_SQL)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        TODO("Not yet implemented")
    }
    fun insertData(record: Record):Long{
        val db = writableDatabase
        val values = ContentValues()
        values.put("title", record.title)
        values.put("affair", record.affair)
        values.put("create_time", record.createTime)
        return db.insert(TABLE_NAME_NOTE, null, values)
    }


    @SuppressLint("Range")
    fun queryAllFromDb(): List<Record> {
        val db = writableDatabase
        val recordList:MutableList<Record> = ArrayList()
        val cursor = db.query(TABLE_NAME_NOTE, null, null, null, null, null, null)
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val id = cursor.getString(cursor.getColumnIndex("id"))
                val title = cursor.getString(cursor.getColumnIndex("title"))
                val affair = cursor.getString(cursor.getColumnIndex("affair"))
                val createTime = cursor.getString(cursor.getColumnIndex("create_time"))
                val record = Record()
                record.id = id
                record.title = title
                record.affair = affair
                record.createTime = createTime
                recordList.add(record)
            }
            cursor.close()
        }
        return recordList
    }
}